package com.jinglvhuanjing.app.widget;

import android.content.Context;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.util.Log;
import android.view.LayoutInflater;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.widget.AppCompatTextView;

import com.jinglvhuanjing.app.R;
import com.jinglvhuanjing.app.bean.LogEvent;
import com.jinglvhuanjing.app.bean.RunEvent;
import com.jinglvhuanjing.app.bean.SheetBottomBean;
import com.jinglvhuanjing.app.utils.ByteUtil;
import com.jinglvhuanjing.app.utils.LOG;
import com.jinglvhuanjing.app.utils.SerialMsgHandler;
import com.jinglvhuanjing.app.utils.SingletonSerl;
import com.jinglvhuanjing.app.utils.StringUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.io.IOException;
import java.util.ArrayList;

public class ParamSettingTermTkView extends androidx.constraintlayout.widget.ConstraintLayout {
    private String TAG = "参数设置";
    private String mLabel = "";
    private String mTKDZ = "";// 投口地址

    public ParamSettingTermTkView(@NonNull Context context) {
        super(context);
        this.init(context);
    }

    public ParamSettingTermTkView(@NonNull Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        this.init(context);
    }

    public ParamSettingTermTkView(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        this.init(context);
    }

    /*** label ***/
    private AppCompatTextView param_setting_term_label;
    private AppCompatTextView param_setting_term_label2;
    private AppCompatTextView param_setting_term_label3;
    private AppCompatTextView param_setting_term_label4;

    /*** 设置按钮 ***/
    private ButtonView device_button_1;
    /*** 投口类型 ***/
    private MySpinnerView spinner_1;
    /*** 距离限值(cm) ***/
    private CustomEdtView param_1;
    /*** 电流限值(mA) ***/
    private CustomEdtView param_2;
    /*** 闭门时间(ms) ***/
    private CustomEdtView param_3;

    /*** 解析收到的投口信息 ***/
    Handler mHandlerSz = new Handler(Looper.myLooper()) {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 0:
                    String obj = (String) msg.obj;
                    if (!StringUtils.isEmpty(obj)) {
                        byte[] bytes_ = ByteUtil.hexStringToBytes(obj);
                        if (bytes_ != null && bytes_.length>1) {
                            // 03 功能码，轮询信息返回
                            if (bytes_[1] == SingletonSerl.byte_gnm_cssz && bytes_.length > 7) {
                                LOG.e(TAG, "读取内容:" + obj);
                                parseByte(bytes_);
                            }
                        }
                    }
                    break;
                default:
                    break;
            }
        }
    };

    @Subscribe
    public void onEvent(RunEvent event) {
        String hex = ByteUtil.hexBytesToString(event.getValue());
        LOG.e(SerialMsgHandler.TAG, TAG+"-读取内容:" + hex);
        Message message = this.mHandlerSz.obtainMessage();
        message.what = 0;
        message.obj = hex;
        this.mHandlerSz.sendMessage(message);
    }

    /**
     * @param bytes
     */
    public void parseByte(byte[] bytes) {
        LogEvent logEvent = new LogEvent();
        logEvent.setTAG(TAG);
        String jcqdz = ByteUtil.hexBytesToString(new byte[]{bytes[2], bytes[3]});
        LOG.e(TAG, "寄存器地址："+jcqdz);
        String lx = SingletonSerl.getJCQDZLX_CSSZ(jcqdz);
        LOG.e(TAG, "类型："+lx);
        // 还要判断投口地址是否对等
        if (!"未知".equals(lx) && ByteUtil.hexByteToString(bytes[0]).equals(this.mTKDZ)) {
            String end = SingletonSerl.getJCQDZFromLX(lx, jcqdz);
            String bw = ByteUtil.hexBytesToString(bytes);
            logEvent.setValue(
                    String.format("【%s号投口】<%s>设置%s:%s"
                            , ByteUtil.hexByteToString(bytes[0])
                            , lx
                            , end
                            , StringUtils.subStringToSpace(bw, 2))
            );
            EventBus.getDefault().post(logEvent);
        }
    }

    private void init(Context context) {
        setClipChildren(false);
        LayoutInflater.from(context).inflate(R.layout.view_param_setting_term_tk, this, true);
        param_setting_term_label = findViewById(R.id.param_setting_term_label);
        param_setting_term_label2 = findViewById(R.id.param_setting_term_label2);
        param_setting_term_label3 = findViewById(R.id.param_setting_term_label3);
        param_setting_term_label4 = findViewById(R.id.param_setting_term_label4);
        device_button_1 = findViewById(R.id.device_button_1);
        spinner_1 = findViewById(R.id.spinner_1);
        param_1 = findViewById(R.id.param_1);
        param_2 = findViewById(R.id.param_2);
        param_3 = findViewById(R.id.param_3);

        SerialMsgHandler.getInstance().setStartListener(true, this.mHandlerSz);
        EventBus.getDefault().register(this);
    }

    public void onDestroy() {
        try {
            EventBus.getDefault().unregister(this);
        }catch (Exception e){

        }
    }

    /**
     * 设置参数标识
     *
     * @param label 按钮中文名称
     * @param key   投口地址(十六进制字符串)
     */
    public void setLabel(String label, String key) {
        this.mLabel = label;
        this.mTKDZ = key;
        Log.d(TAG, String.format("%s_投口地址%s", label, key));
        if (TextUtils.isEmpty(label)) {
            return;
        }
        this.device_button_1.setText(label);
        this.device_button_1.setParamTag(label, key);
        this.device_button_1.setButtonClickEvent((label1, key1) -> {
            onClickWrite();
        });

        ArrayList<SheetBottomBean> items = new ArrayList<>();
//        0x01其他垃圾，0x02，厨余垃圾，0x03可回收垃圾，0x04纸张，0x05金属，0x06塑料，0x07玻璃
        items.add(new SheetBottomBean("不选择", ""));
        items.add(new SheetBottomBean("其他垃圾", "01"));
        items.add(new SheetBottomBean("厨余垃圾", "02"));
        items.add(new SheetBottomBean("可回收垃圾", "03"));
        items.add(new SheetBottomBean("纸张", "04"));
        items.add(new SheetBottomBean("金属", "05"));
        items.add(new SheetBottomBean("塑料", "06"));
        items.add(new SheetBottomBean("玻璃", "07"));
        // 设置投口类型列表
        spinner_1.setData(items);
    }

    public void setTkVisible(boolean visible) {
        this.param_setting_term_label.setVisibility(visible ? VISIBLE : GONE);
        this.param_setting_term_label2.setVisibility(visible ? VISIBLE : GONE);
        this.param_setting_term_label3.setVisibility(visible ? VISIBLE : GONE);
        this.param_setting_term_label4.setVisibility(visible ? VISIBLE : GONE);
    }

    private void onClickWrite() {
        String tkLx = spinner_1.getValue();
        String jlz = param_1.getText().toString();
        String dlxz = param_2.getText().toString();
        String bmsj = param_3.getText().toString();
//        if(StringUtils.isEmpty(tkLx)){Toast.makeText(getContext(), "请先选择投口类型", Toast.LENGTH_SHORT).show();return;}
//        else if(StringUtils.isEmpty(jlz)){Toast.makeText(getContext(), "请先填写距离值", Toast.LENGTH_SHORT).show();return;}
//        else if(StringUtils.isEmpty(dlxz)){Toast.makeText(getContext(), "请先填写电流限值", Toast.LENGTH_SHORT).show();return;}
//        else if(StringUtils.isEmpty(bmsj)){Toast.makeText(getContext(), "请先填写闭门时间", Toast.LENGTH_SHORT).show();return;}
        LOG.e(TAG, String.format("%s_投口地址%s,投口类型%s(%s),距离值%s,电流限值%s,闭门时间%s",
                mLabel, mTKDZ, spinner_1.getLabel(), tkLx, jlz, dlxz, bmsj));

        try {
            SingletonSerl singletonSerl = SingletonSerl.getInstance();
            if (!StringUtils.isEmpty(tkLx)) {
                LOG.e(TAG, "投口类型参数设置");
                String bw = singletonSerl.write(TAG, singletonSerl.deviceSettingTK(mTKDZ, tkLx));
                eventBus(mTKDZ, "投口类型", bw);
            }

            if (!StringUtils.isEmpty(jlz)) {
                LOG.e(TAG, "距离限值类型参数设置");
                String jlzHex = ByteUtil.intToHex(Integer.parseInt(jlz));
                String bw = singletonSerl.write(TAG, singletonSerl.deviceSettingJLXZ(mTKDZ, ByteUtil.String_0(jlzHex, 4)));
                eventBus(mTKDZ, "距离限值", bw);
            }

            if (!StringUtils.isEmpty(dlxz)) {
                LOG.e(TAG, "电流限值类型参数设置");
                String dlzHex = ByteUtil.intToHex(Integer.parseInt(dlxz));
                String bw = singletonSerl.write(TAG, singletonSerl.deviceSettingDLXZ(mTKDZ, ByteUtil.String_0(dlzHex, 4)));
                eventBus(mTKDZ, "电流限值", bw);
            }

            if (!StringUtils.isEmpty(bmsj)) {
                LOG.e(TAG, "闭门时间类型参数设置");
                String bmHex = ByteUtil.intToHex(Integer.parseInt(bmsj));
                String bw = singletonSerl.write(TAG, singletonSerl.deviceSettingBMSJ(mTKDZ, ByteUtil.String_0(bmHex, 4)));
                eventBus(mTKDZ, "闭门时间", bw);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void eventBus(String tkdz, String type, String bw) {
        LogEvent logEvent = new LogEvent();
        logEvent.setTAG(TAG);
        logEvent.setValue(
                String.format("【%s号投口】<%s>发送:%s"
                        , ByteUtil.hexStringToInt(tkdz)
                        , type
                        , StringUtils.subStringToSpace(bw, 2)));
        EventBus.getDefault().post(logEvent);
    }
}
